﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;

namespace WpfConsole
{
    public class VisualGrid
    {
        struct Position
        {
            public int Row { get; set; } public int Column { get; set; }
        }
        Dictionary<Position, DrawingVisual> _dict = new Dictionary<Position, DrawingVisual>();
        private VisualCollection _visCollection;
        private int _maxColumns;
        private int _maxRows;

        public VisualGrid(VisualCollection col)
        {
            _visCollection = col;
        }


        public void Resize(int newColumn, int newRow)
        {
            if (_maxRows > newRow)
            {
                for (int row = newRow; row < _maxRows; row++)
                {
                    for (int col = 0; col < _maxColumns; col++)
                    {
                        Position pos = new Position() { Row = row, Column = col };
                        if (_dict.Keys.Contains(pos))
                        {
                            Visual vis = _dict[pos];
                            _visCollection.Remove(vis);
                            _dict.Remove(pos);
                        }
                    }
                }
            }
            if (_maxColumns > newColumn)
            {
                for (int row = 0; row < _maxRows; row++)
                {
                    for (int col = newColumn; col < _maxColumns; col++)
                    {
                        Position pos = new Position() { Row = row, Column = col };
                        if (_dict.Keys.Contains(pos))
                        {
                            Visual vis = _dict[pos];
                            _visCollection.Remove(vis);
                            _dict.Remove(pos);
                        }
                    }
                }
            }
        }

        public DrawingVisual Visual(int column, int row)
        {
            _maxColumns = Math.Max(column+1, _maxColumns);
            _maxRows = Math.Max(row+1, _maxRows);

            Position pos = new Position() { Row = row, Column = column };

            if (!_dict.ContainsKey(pos))
            {
                DrawingVisual vis = new DrawingVisual();
                _dict[pos] = vis;
                _visCollection.Add(vis);
            }
            return _dict[pos];
        }
    }
}
